{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import open_clip\n",
    "from collections import OrderedDict\n",
    "import torch\n",
    "\n",
    "model, _, preprocess = open_clip.create_model_and_transforms('ViT-L-14', pretrained='datacomp_xl_s13b_b90k')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(model.logit_scale.exp())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(preprocess)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(model.state_dict()[\"visual.proj\"].shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "new_state_dict = OrderedDict()\n",
    "for k, v in model.state_dict().items():\n",
    "    if 'visual.' in k:\n",
    "        new_state_dict[k[7:]] = v\n",
    "torch.save(new_state_dict, '{openclip_path}/datacomp_xl_s13b_b90k/vit_l14.pth')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "new_state_dict = OrderedDict()\n",
    "for k, v in model.state_dict().items():\n",
    "    if not 'visual.' in k and not 'logit_scale' in k:\n",
    "        new_state_dict[k] = v\n",
    "torch.save(new_state_dict, '{openclip_path}/datacomp_xl_s13b_b90k/vit_l14_text.pth')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test the extracted models\n",
    "\n",
    "from models.backbones.clip.clip_vision import clip_joint_l14\n",
    "from models.backbones.clip.clip_text import clip_text_l14\n",
    "\n",
    "visual_encoder = clip_joint_l14(num_frames=1)\n",
    "text_encoder = clip_text_l14(context_length=32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torchvision import transforms\n",
    "from torchvision.transforms import InterpolationMode\n",
    "import decord\n",
    "import numpy as np\n",
    "\n",
    "def load_video(path):\n",
    "    video_reader = decord.VideoReader(path, num_threads=1, ctx=decord.cpu(0))\n",
    "    decord.bridge.set_bridge('torch')\n",
    "    video_len = len(video_reader)\n",
    "    video = video_reader.get_batch(np.linspace(0, video_len - 1, 1).astype(np.int)).byte()\n",
    "    video = video.permute(0, 3, 1, 2)\n",
    "\n",
    "    return video\n",
    "\n",
    "# This transform follows vindlu\n",
    "type_transform = transforms.Lambda(lambda x: x.float().div(255.0))\n",
    "mean = (0.48145466, 0.4578275, 0.40821073)\n",
    "std = (0.26862954, 0.26130258, 0.27577711)\n",
    "normalize = transforms.Normalize(mean, std)\n",
    "transform = transforms.Compose(\n",
    "        [\n",
    "            transforms.Resize(\n",
    "                (224, 224),\n",
    "                interpolation=InterpolationMode.BICUBIC,\n",
    "            ),\n",
    "            type_transform,\n",
    "            normalize,\n",
    "        ]\n",
    ")\n",
    "\n",
    "video = load_video('examples/yoga.mp4')\n",
    "video = transform(video)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn.functional as F\n",
    "\n",
    "visual_embedding = visual_encoder(video.permute(1, 0, 2, 3).unsqueeze(0))\n",
    "text = text_encoder.tokenize(['a woman doing yoga', 'a woman doing yoga on the roof', 'a man doing yoga', 'a person doing yoga', 'a dog running on the grass', 'a cat sitting on the sofa'])\n",
    "text_embedding = text_encoder(text)\n",
    "\n",
    "visual_embedding = F.normalize(visual_embedding, dim=-1, p=2)\n",
    "text_embedding = F.normalize(text_embedding, dim=-1, p=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(visual_embedding.shape, text_embedding.shape)\n",
    "print((100 * visual_embedding @ text_embedding.T).softmax(-1))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
